using ETask.Api.Data;
using ETask.Api.Dtos;
using ETask.Api.Models;
using Microsoft.EntityFrameworkCore;

namespace ETask.Api.Repositories
{
    /// <summary>
    /// 审计日志仓储实现
    /// </summary>
    public class AuditLogRepository : Repository<AuditLog>, IAuditLogRepository
    {
        public AuditLogRepository(AppDbContext context) : base(context)
        {
        }

        /// <summary>
        /// 分页查询审计日志
        /// </summary>
        public async Task<PagedResult<AuditLogDto>> GetPagedListAsync(AuditLogQueryParams queryParams)
        {
            var query = _context.AuditLogs.AsQueryable();

            // 按操作类型筛选
            if (!string.IsNullOrEmpty(queryParams.ActionType))
            {
                query = query.Where(x => x.ActionType == queryParams.ActionType);
            }

            // 按模块筛选
            if (!string.IsNullOrEmpty(queryParams.Module))
            {
                query = query.Where(x => x.Module == queryParams.Module);
            }

            // 按关键词搜索
            if (!string.IsNullOrEmpty(queryParams.Keyword))
            {
                var keyword = queryParams.Keyword.ToLower();
                query = query.Where(x => 
                    x.Description.ToLower().Contains(keyword) ||
                    x.UserName.ToLower().Contains(keyword) ||
                    x.Account.ToLower().Contains(keyword) ||
                    x.TargetName.ToLower().Contains(keyword));
            }

            // 按时间范围筛选
            if (queryParams.StartTime.HasValue)
            {
                query = query.Where(x => x.ActionTime >= queryParams.StartTime.Value);
            }

            if (queryParams.EndTime.HasValue)
            {
                query = query.Where(x => x.ActionTime <= queryParams.EndTime.Value);
            }

            // 按用户ID筛选
            if (queryParams.UserId.HasValue)
            {
                query = query.Where(x => x.UserId == queryParams.UserId.Value);
            }

            // 按操作结果筛选
            if (!string.IsNullOrEmpty(queryParams.Result))
            {
                query = query.Where(x => x.Result == queryParams.Result);
            }
            var res = await  query
                .OrderByDescending(x => x.ActionTime)
                .Select(x => new AuditLogDto
                {
                    Id = x.Id,
                    ActionType = x.ActionType,
                    Module = x.Module,
                    Description = x.Description,
                    UserId = x.UserId,
                    UserName = x.UserName,
                    Account = x.Account,
                    TargetId = x.TargetId,
                    TargetName = x.TargetName,
                    OldValues = x.OldValues,
                    NewValues = x.NewValues,
                    ClientIp = x.ClientIp,
                    UserAgent = x.UserAgent,
                    Result = x.Result,
                    ErrorMessage = x.ErrorMessage,
                    ActionTime = x.ActionTime,
                    CreatedAt = x.CreatedAt,
                    UpdatedAt = x.UpdatedAt
                }).ToPagedResultAsync<AuditLogDto>(queryParams.PageDto);
            return res;
        }

        /// <summary>
        /// 根据用户ID获取最近的日志
        /// </summary>
        public async Task<List<AuditLogDto>> GetRecentLogsByUserIdAsync(int userId, int count = 10)
        {
            return await _context.AuditLogs
                .Where(x => x.UserId == userId)
                .OrderByDescending(x => x.ActionTime)
                .Take(count)
                .Select(x => new AuditLogDto
                {
                    Id = x.Id,
                    ActionType = x.ActionType,
                    Module = x.Module,
                    Description = x.Description,
                    UserId = x.UserId,
                    UserName = x.UserName,
                    Account = x.Account,
                    TargetId = x.TargetId,
                    TargetName = x.TargetName,
                    OldValues = x.OldValues,
                    NewValues = x.NewValues,
                    ClientIp = x.ClientIp,
                    UserAgent = x.UserAgent,
                    Result = x.Result,
                    ErrorMessage = x.ErrorMessage,
                    ActionTime = x.ActionTime,
                    CreatedAt = x.CreatedAt,
                    UpdatedAt = x.UpdatedAt
                })
                .ToListAsync();
        }
    }
}
